package com.hj.ipproxy.httpclient;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.zip.GZIPInputStream;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;

import com.hj.ipproxy.bean.HttpEntity;
import com.hj.ipproxy.config.ConfigrurationMgr;
import com.hj.tools.StringUtil;

public class HttpClientManager {
	/**
	 * GET请求
	 * @param ht
	 */
	public static void doGet(HttpEntity ht){
		if (TcpType.GET_HTTP_PROXY == ht.getTcpType()) {
			doGetHTTPByProxy(ht);
		}else if (TcpType.GET_HTTPS == ht.getTcpType()) {
			doGetHTTPS(ht);
		} else if (TcpType.GET_HTTPS_PROXY == ht.getTcpType()) {
			doGetHTTPSByProxy(ht);
		}else{
			doGetHTTP(ht);
		}
	}
	
	/**
	 * 发送HTTP-GET请求
	 * @param ht
	 */
	private static void doGetHTTP(HttpEntity ht){
		URLConnection conn = null;
		URL url = null;
		try {
			url = new URL(ht.getUrl());
			conn = url.openConnection();
			conn.setConnectTimeout(ht.getConnecttimerout());
			conn.setReadTimeout(ht.getReadtimeout());
			conn.setRequestProperty("User-Agent",ht.getUserAgent());
			
			ht.setStarttime();
			String body = parseBody(conn.getInputStream(), conn.getContentEncoding()!=null, ht);
			ht.setBody(body);
		} catch(SocketTimeoutException timeout){
			System.err.println("连接超时...");
		} catch (ConnectException e) {
			System.err.println("连接异常："+e.getMessage());
		} catch (IOException e) {
			System.err.println("IOException异常："+e.getMessage());
		}finally{
			url = null;
			conn = null;
		}
	}
	
	/**
	 * 通过代理IP发送HTTP-GET请求
	 */
	private static void doGetHTTPByProxy(HttpEntity ht){
		URLConnection conn = null;
		URL url = null;
		try {
			Proxy typeProxy = new Proxy
					(Proxy.Type.HTTP, new InetSocketAddress(ht.getIp(), ht.getPort()));
			url = new URL(ht.getUrl());
			conn = url.openConnection(typeProxy);
			conn.setConnectTimeout(ht.getConnecttimerout());
			conn.setReadTimeout(ht.getReadtimeout());
			conn.setRequestProperty("User-Agent",ht.getUserAgent());
			
			ht.setStarttime();
			InputStream urlStream = conn.getInputStream();
			String body = parseBody(urlStream, conn.getContentEncoding()!=null, ht);
			ht.setBody(body);
		} catch(SocketTimeoutException timeout){
			System.err.println(Thread.currentThread().getName()+"连接超时...");
		} catch (ConnectException e) {
			System.err.println(Thread.currentThread().getName()+"连接异常："+e.getMessage());
		} catch (IOException e) {
			System.err.println(Thread.currentThread().getName()+"IOException异常："+e.getMessage());
		}finally{
			url = null;
			conn = null;
		}
	}
	
	/**
	 * 发送HTTPS-GET请求
	 * @param ht
	 */
	private static void doGetHTTPS(HttpEntity ht){
		URL url = null;
		HttpsURLConnection conn = null;
		try {
			url = new URL(ht.getUrl());
			conn = (HttpsURLConnection) url.openConnection();
			
			SSLContext sc = SSLContext.getInstance("SSL");
			sc.init(null, 
					new TrustManager[] { TrustSSL.getTrustAnyTrustManager() },
					new java.security.SecureRandom());
			conn.setSSLSocketFactory(sc.getSocketFactory());
			conn.setHostnameVerifier(TrustSSL.getHostnameVerifier());
			conn.setConnectTimeout(ht.getConnecttimerout());
			conn.setReadTimeout(ht.getReadtimeout());
			conn.setRequestProperty("User-Agent",ht.getUserAgent());
			
			ht.setStarttime();
			String body = parseBody(conn.getInputStream(), conn.getContentEncoding()!=null, ht);
			ht.setBody(body);
		}catch(SocketTimeoutException timeout){
			System.err.println("连接超时...");
		} catch (ConnectException e) {
			System.err.println("连接异常："+e.getMessage());
		} catch (KeyManagementException e) {
			System.err.println("KeyManagementException异常："+e.getMessage());
		} catch (IOException e) {
			System.err.println("IOException异常："+e.getMessage());
		} catch (NoSuchAlgorithmException e) {
			System.err.println("NoSuchAlgorithmException异常："+e.getMessage());
		}finally{
			url = null;
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
		}
	}
	
	/**
	 * 通过代理IP发送HTTPS-GET请求
	 */
	private static void doGetHTTPSByProxy(HttpEntity ht){
		URL url = null;
		HttpsURLConnection conn = null;
		try {
			url = new URL(ht.getUrl());
			Proxy typeProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ht.getIp(), ht.getPort()));
			conn = (HttpsURLConnection) url.openConnection(typeProxy);
			
			SSLContext sc = SSLContext.getInstance("SSL");
			sc.init(null, 
					new TrustManager[] { TrustSSL.getTrustAnyTrustManager() },
					new java.security.SecureRandom());
			conn.setSSLSocketFactory(sc.getSocketFactory());
			conn.setHostnameVerifier(TrustSSL.getHostnameVerifier());
			conn.setConnectTimeout(ht.getConnecttimerout());
			conn.setReadTimeout(ht.getReadtimeout());
			conn.setRequestProperty("User-Agent",ht.getUserAgent());
			
			ht.setStarttime();
			String body = parseBody(conn.getInputStream(), conn.getContentEncoding()!=null, ht);
			ht.setBody(body);
		} catch(SocketTimeoutException timeout){
			System.err.println("连接超时...");
		} catch (ConnectException e) {
			System.err.println("ConnectException异常："+e.getMessage());
		} catch (KeyManagementException e) {
			System.err.println("KeyManagementException异常："+e.getMessage());
		} catch (IOException e) {
			System.err.println("IOException异常："+e.getMessage());
		} catch (NoSuchAlgorithmException e) {
			System.err.println("NoSuchAlgorithmException异常："+e.getMessage());
		}finally{
			url = null;
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
		}
	}
	
	/**
	 * 获取自己当前的IP
	 * @return
	 */
	public static String getMyIp(){
		String myIp = null;
		HttpEntity ht = new HttpEntity(ConfigrurationMgr.getValidateUrl());
		ht.setCharset("GB2312");
		if (ht.send()) {
			String body = ht.getBody();
			String proxyIpInfo = StringUtil.match(body, ">(您的(IP|ip)地址是.+?)<")[1];
			myIp = StringUtil.match(proxyIpInfo, "\\[(.*)\\]")[1];
			System.err.println("自己ＩＰ---"+myIp);
		}
		return myIp;
	}
	
	private static String parseBody(InputStream urlStream, boolean isGzip, HttpEntity ht){
		StringBuffer html = new StringBuffer();
		BufferedInputStream in = null;
		byte[] buf = null;
		try {
			if (isGzip) {
				urlStream = new GZIPInputStream(urlStream);
			}
			in = new BufferedInputStream(urlStream);
			ht.setEndtime();
			buf = new byte[4096];
			int bytesRead = 0;
			while ((bytesRead = in.read(buf)) >= 0) {
				html.append(new String(buf, 0, bytesRead, ht.getCharset()));
			}
		} catch (Exception e) {
			System.out.println("解析响应内容错误: "+e.getMessage());
		}finally{
			try {
				if (buf != null) {
					buf = null;
				}
				if (in != null) {
					in.close();
				}
				if (urlStream != null) {
					urlStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return html.toString();
	}
}
